package com.nursinghome.management.service;

import com.nursinghome.management.model.Staff;
import com.nursinghome.management.model.User;
import com.nursinghome.management.repository.StaffRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StaffService {

    private final StaffRepository staffRepository;

    public StaffService(StaffRepository staffRepository) {
        this.staffRepository = staffRepository;
    }

    public List<Staff> getAllStaff() {
        return staffRepository.findAll();
    }

    public Staff getStaffById(Long id) {
        return staffRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Staff not found with id: " + id));
    }

    public Staff getStaffByUser(User user) {
        return staffRepository.findByUser(user)
                .orElseThrow(() -> new RuntimeException("Staff not found for user: " + user.getUsername()));
    }

    public Staff createStaff(Staff staff) {
        return staffRepository.save(staff);
    }

    public Staff updateStaff(Staff staff) {
        Staff existingStaff = staffRepository.findById(staff.getId())
                .orElseThrow(() -> new RuntimeException("Staff not found with id: " + staff.getId()));

        existingStaff.setPosition(staff.getPosition());
        existingStaff.setDepartment(staff.getDepartment());
        existingStaff.setQualification(staff.getQualification());
        existingStaff.setJoiningDate(staff.getJoiningDate());
        existingStaff.setContactNumber(staff.getContactNumber());
        existingStaff.setEmergencyContact(staff.getEmergencyContact());

        return staffRepository.save(existingStaff);
    }

    public void deleteStaff(Long id) {
        staffRepository.deleteById(id);
    }
}